import { BrowserRouter, Routes, Route, useLocation, Navigate } from 'react-router-dom'
import Page from './page'
import { RouterType } from '../interface'
import { getCookie } from '../utils'

const Router = () => {

    // 路由拦截器
    const BeforeEach = (props: { children: JSX.Element }) => {

        const location = useLocation()

        // 拦截
        if(!getCookie() && location.pathname !== '/login') {
            return <Navigate to='/login' />
        } 

        return props.children
    }

    const renderRouter = (router: RouterType[]) => {
        return router.map((item, idx) => {
            return <Route key={idx} path={item.path} element={<BeforeEach>{item.element}</BeforeEach>}>
                {item.children && renderRouter(item.children)}
            </Route>
        })
    }

    return <BrowserRouter>
        <Routes>
            {
                renderRouter(Page)
            }
        </Routes>
    </BrowserRouter>
}


export default Router